<template>
  <div class="calendar">
    <h2>打卡日历</h2>
    
    <!-- 月份导航 -->
    <div class="month-nav">
      <button @click="previousMonth">&lt;</button>
      <span>{{ currentYear }}年 {{ currentMonth + 1 }}月</span>
      <button @click="nextMonth">&gt;</button>
    </div>

    <!-- 日历网格 -->
    <div class="calendar-grid">
      <div class="weekday" v-for="day in weekdays" :key="day">{{ day }}</div>
      <div
        v-for="(day, index) in calendarDays"
        :key="index"
        class="day"
        :class="{
          'other-month': day.otherMonth,
          'has-records': day.hasRecords,
          'today': isToday(day.date)
        }"
        @click="viewDayDetails(day)"
      >
        <span class="date">{{ day.date.getDate() }}</span>
        <div class="records-indicator" v-if="day.hasRecords">
          <span class="dot"></span>
        </div>
      </div>
    </div>

    <!-- 日期详情弹窗 -->
    <div v-if="showDayDetails" class="day-details-modal">
      <div class="modal-content">
        <h3>{{ formatDate(selectedDay.date) }}打卡记录</h3>
        <div v-for="record in dayRecords" :key="record.id" class="record-item">
          <p>{{ record.habit_name }}</p>
          <p>时长: {{ record.duration }}分钟</p>
          <p>积分: {{ record.points_earned }}</p>
        </div>
        <button @click="showDayDetails = false">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Calendar',
  props: {
    childId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      currentDate: new Date(),
      weekdays: ['日', '一', '二', '三', '四', '五', '六'],
      calendarDays: [],
      records: {},
      showDayDetails: false,
      selectedDay: null,
      dayRecords: []
    }
  },
  computed: {
    currentYear() {
      return this.currentDate.getFullYear()
    },
    currentMonth() {
      return this.currentDate.getMonth()
    }
  },
  methods: {
    async fetchMonthRecords() {
      try {
        const response = await axios.get(
          `http://localhost:5000/api/calendar/${this.childId}`,
          {
            params: {
              year: this.currentYear,
              month: this.currentMonth + 1
            }
          }
        )
        this.records = response.data
        this.generateCalendar()
      } catch (error) {
        console.error('获取月度记录失败:', error)
      }
    },
    generateCalendar() {
      const firstDay = new Date(this.currentYear, this.currentMonth, 1)
      const lastDay = new Date(this.currentYear, this.currentMonth + 1, 0)
      const days = []

      // 填充上个月的日期
      const firstDayWeekday = firstDay.getDay()
      for (let i = firstDayWeekday - 1; i >= 0; i--) {
        const date = new Date(firstDay)
        date.setDate(date.getDate() - i)
        days.push({
          date,
          otherMonth: true,
          hasRecords: false
        })
      }

      // 填充当前月的日期
      for (let i = 1; i <= lastDay.getDate(); i++) {
        const date = new Date(this.currentYear, this.currentMonth, i)
        const dateString = date.toISOString().split('T')[0]
        days.push({
          date,
          otherMonth: false,
          hasRecords: this.records[dateString]?.length > 0
        })
      }

      this.calendarDays = days
    },
    previousMonth() {
      this.currentDate = new Date(this.currentYear, this.currentMonth - 1)
      this.fetchMonthRecords()
    },
    nextMonth() {
      this.currentDate = new Date(this.currentYear, this.currentMonth + 1)
      this.fetchMonthRecords()
    },
    async viewDayDetails(day) {
      this.selectedDay = day
      if (!day.otherMonth) {
        const dateString = day.date.toISOString().split('T')[0]
        try {
          const response = await axios.get(
            `http://localhost:5000/api/calendar/${this.childId}/day`,
            { params: { date: dateString } }
          )
          this.dayRecords = response.data
          this.showDayDetails = true
        } catch (error) {
          console.error('获取日期详情失败:', error)
        }
      }
    },
    isToday(date) {
      const today = new Date()
      return date.toDateString() === today.toDateString()
    },
    formatDate(date) {
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
    }
  },
  mounted() {
    this.fetchMonthRecords()
  }
}
</script>

<style scoped>
.calendar {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.month-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  background: #ddd;
  border: 1px solid #ddd;
}

.weekday {
  background: #f5f5f5;
  padding: 10px;
  text-align: center;
  font-weight: bold;
}

.day {
  background: white;
  padding: 10px;
  min-height: 80px;
  position: relative;
  cursor: pointer;
}

.day:hover {
  background: #f9f9f9;
}

.other-month {
  opacity: 0.5;
}

.today {
  background: #e8f5e9;
}

.has-records .dot {
  width: 6px;
  height: 6px;
  background: #42b983;
  border-radius: 50%;
  display: inline-block;
}

.day-details-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  max-width: 400px;
  width: 90%;
}

.record-item {
  border-bottom: 1px solid #eee;
  padding: 10px 0;
}
</style> 